package com.baidu.lib_home.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.marginTop
import androidx.core.view.setPadding
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.baidu.lib_audio.AudioController
import com.baidu.lib_common.PlayMode
import com.baidu.lib_common.R
import com.baidu.lib_common.animator.rotate
import com.baidu.lib_common.animator.rotate20Angle
import com.baidu.lib_common.animator.rotateAbs20Angle
import com.baidu.lib_common.animator.stopRotate
import com.baidu.lib_common.animator.toRotateAngle
import com.baidu.lib_common.base.BaseFragment
import com.baidu.lib_common.constant.AudioChangeEvent
import com.baidu.lib_common.constant.AudioOverEvent
import com.baidu.lib_common.constant.AudioPauseEvent
import com.baidu.lib_common.constant.AudioPlayModeChangeEvent
import com.baidu.lib_common.constant.AudioProgressUpdateEvent
import com.baidu.lib_common.constant.AudioStartEvent
import com.baidu.lib_common.utils.getStatusBarHeight
import com.baidu.lib_common.utils.loadurl
import com.baidu.lib_common_ui.utils.getPlayTimeString
import com.baidu.lib_home.databinding.MusicPlayBinding
import com.baidu.lib_home.viewmodel.MainViewModel
import com.baidu.lib_leancloud.AudioFavoriteChangeEvent
import com.baidu.lib_leancloud.db.FavoriteViewModel
import com.baidu.lib_leancloud.db.RoomHelper
import com.baidu.lib_leancloud.model.Music
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.random.Random

class MusicPlayFragment: BaseFragment<MusicPlayBinding>() {
    val mainViewModel: MainViewModel by activityViewModels()
    val favoriteViewModel: FavoriteViewModel by activityViewModels()
    lateinit var music: Music


    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun initUI(savedInstanceState: Bundle?) {
        super.initUI(savedInstanceState)
        mainViewModel.currentMusic.observe(viewLifecycleOwner){
            music = it
            initFragment()

        }
        initEvent()

    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
        mBinding.albumView.stopRotate()
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioStartEvent(event: AudioStartEvent){
        mBinding.playView.setImageResource(R.drawable.audio_stop)
        mBinding.indicatorView.rotate20Angle()
        mBinding.albumView.rotate()
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioEndEvent(event: AudioPauseEvent){
        mBinding.playView.setImageResource(R.drawable.audio_play)
        mBinding.indicatorView.rotateAbs20Angle()
        mBinding.albumView.stopRotate()
    }
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    fun OnAudioPlayModeChangeEvent(event: AudioPlayModeChangeEvent){
        var imageId = 0
        when(event.mode){
            PlayMode.RANDOM -> {
                imageId = R.drawable.audio_mode_random
            }

            PlayMode.REPEAT -> {
                imageId = R.drawable.audio_mode_recycle
            }
            PlayMode.LOOP -> {
                imageId = R.drawable.audio_mode_list_cycle
            }
            PlayMode.INFINITE -> {
                imageId = R.drawable.audio_mode_infinite
            }
        }
        mBinding.modeView.setImageResource(imageId)
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioFavoriteChangeEvent(event: AudioFavoriteChangeEvent){
        if(event.isFavorite){
            mBinding.favoriteView.setImageResource(R.drawable.audio_selected_love)
        }else{
            mBinding.favoriteView.setImageResource(R.drawable.audio_love)
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun OnAudioProgressUpdateEvent(event: AudioProgressUpdateEvent){
        showProgress()

    }
    fun initFragment(){
        mBinding.titleView.text = music.name
        mBinding.authorView.text = music.singer
        mBinding.albumView.loadurl(music.image,true)
        mBinding.albumView.toRotateAngle()
        if(RoomHelper.sharedFavoriteViewModel!!.isFavorite(music.id)){
            mBinding.favoriteView.setImageResource(R.drawable.audio_selected_love)
        }else{
            mBinding.favoriteView.setImageResource(R.drawable.audio_love)
        }

        if(AudioController.instance.isPlaying()){
            mBinding.playView.setImageResource(R.drawable.audio_stop)
            mBinding.indicatorView.rotate20Angle()
            mBinding.albumView.rotate()
        }
        mBinding.closeView.setOnClickListener{
            findNavController().popBackStack()
        }

        showMusicTime(music)
    }
    //定义音乐播放完毕事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAudioOverEvent(event: AudioOverEvent) {
        //调用下一首
        AudioController.instance.next()
    }

    //显示播放进度时间
    private fun showProgress() {
        val music = AudioController.Companion.instance.getCurrentPlayingMusic()
        //显示当前进度对应的时间
        mBinding.timeStartView.text = getPlayTimeString(music.progress)
        //更新进度条
        mBinding.progressView.updateProgress(music.progress.toFloat() / music.duration)
        //判断是否播完
        if(music.progress.toFloat() / music.duration >= 0.999){
            EventBus.getDefault().post(AudioOverEvent())
        }
    }


    //显示音乐时长
    private fun showMusicTime(music: Music) {
        //显示音乐总时长
        mBinding.timeEndView.text = getPlayTimeString(music.duration)
    }
    fun initEvent(){
        mBinding.playView.setOnClickListener{
            AudioController.instance.startOrPause()
        }
        mBinding.previousView.setOnClickListener{
            AudioController.instance.previous()
        }
        mBinding.nextView.setOnClickListener{
            AudioController.instance.next()
        }
        mBinding.modeView.setOnClickListener{
            AudioController.instance.changePlayMode()
        }
        mBinding.favoriteView.setOnClickListener{
            favoriteViewModel.changeFavoriteMusic(music.id)
        }
        mBinding.playListView.setOnClickListener{
            findNavController().navigate(com.baidu.lib_home.R.id.action_musicPlayFragment_to_musicListFragment)
        }
        mBinding.singView.setOnClickListener{
            Toast.makeText(requireContext(),"歌手: ${music.singer}, 专辑: ${music.album}",Toast.LENGTH_SHORT).show()
        }
        mBinding.progressView.setOnSeekListener(onStart = {
            //暂停播放
            AudioController.Companion.instance.pause()
        }, onStop = { rate ->
            //progress
            //duration
            //rate
            val music = AudioController.Companion.instance.getCurrentPlayingMusic()
            //计算rate对应的时间值
            val seekProgress = (rate * music.duration).toInt()
            //获取音乐应该播放的位置
            val position = music.progress + seekProgress
            //更新播放器
            AudioController.Companion.instance.seekTo(position)

            //开始播放
            AudioController.Companion.instance.start()
        })
    }

}